package com.fengba.nanzhi.myinfo;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import com.fengba.nanzhi.fengba.R;
import com.fengba.nanzhi.login.Login;
import com.fengba.nanzhi.notice.Notice;
import com.fengba.nanzhi.notice.NoticeAdapter;
import com.fengba.nanzhi.utils.FX_SignInUtil;
import com.fengba.nanzhi.utils.OKManager;
import com.fengba.nanzhi.utils.Preferences;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by SpakeBrony on 2018/4/9.
 */

public class WxImg extends Activity {


    private String url;

    private ImageView WXimg01;

    Boolean  up=true;//默认false不刷新

    protected static final int CAMERA_REQUEST_CODE = 0;
    protected static final int ALBUM_REQUEST_CODE = 1;
    private static final int CROP_REQUEST_CODE = 2;




    //在消息队列中实现对控件的更改
    private Handler handle = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Bitmap bmp=(Bitmap)msg.obj;
                    WXimg01.setImageBitmap(bmp);
                    break;
            }
        };
    };

    public WxImg() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fx_wx_img);
        WXimg01 = (ImageView) findViewById(R.id.WXimg01);
        String wechat_qr_code = null;
        try {
            Object user_info = Preferences.getParam(WxImg.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            wechat_qr_code = myJson.get("wechat_qr_code").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        url=wechat_qr_code;
        /**
         * 返回
         */
        ImageButton WIbtn01 = (ImageButton)findViewById(R.id.WIbtn01);
        WIbtn01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                //getActivity().overridePendingTransition(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            }
        });



        /**
         * 上传二维码
         */
        Button WIbtn02 = (Button) findViewById(R.id.WIbtn02);
        WIbtn02.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                /**这里有2种获取相册的方式*/
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                //Intent intent = new Intent(Intent.ACTION_PICK, null);
                //intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, ALBUM_REQUEST_CODE);

            }
        });



        //刷新界面
        final RefreshLayout refreshLayout = (RefreshLayout)findViewById(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {

            public void onRefresh(RefreshLayout refreshlayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(false) {
                            Toast.makeText(WxImg.this, "刷新失败", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        }else{
                            new Thread(new Runnable() {

                                @Override
                                public void run() {
                                    Bitmap bmp = getURLimage(url);
                                    Message msg = new Message();
                                    msg.what = 0;
                                    msg.obj = bmp;
                                    handle.sendMessage(msg);
                                }
                            }).start();
                            Toast.makeText(WxImg.this, "刷新完毕", Toast.LENGTH_SHORT).show();
                            refreshLayout.finishRefresh();
                        }
                        /**
                         * 刷新完成后调用此方法，要不然刷新效果不消失
                         */

                    }
                }, 0);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
    }//都在这里打

    //加载图片
    public Bitmap getURLimage(String url) {
        Bitmap bmp = null;
        try {
            URL myurl = new URL(url);
            // 获得连接
            HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
            conn.setConnectTimeout(6000);//设置超时
            conn.setDoInput(true);
            conn.setUseCaches(true);//不缓存
            conn.connect();
            InputStream is = conn.getInputStream();//获得图片的数据流
            bmp = BitmapFactory.decodeStream(is);
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bmp;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_CANCELED)
                return;
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                Bitmap bitmap = bundle.getParcelable("data");
                Uri uri = saveBitmap(bitmap);
                startImageZoom(uri);
            }
        } else if (requestCode == ALBUM_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_CANCELED)
                return;
            Uri uri = data.getData();
            Uri fileUri = converUri(uri);
            startImageZoom(fileUri);
        } else if (requestCode == CROP_REQUEST_CODE) {
            Bundle bundle = data.getExtras();
            Bitmap bitmap = bundle.getParcelable("data");
            WXimg01.setImageBitmap(bitmap);
            sendImage(bitmap);
        }
    }

    /**
     * 裁剪
     * @param uri
     */
    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", true);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }

    /**
     * 将Content的Uri转成file的Uri
     *
     * @param uri
     * @return
     */
    private Uri converUri(Uri uri) {
        InputStream in = null;
        try {
            in = getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(in);
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将Bitmap转成file的Uri
     *
     * @param bitmap
     * @return
     */
    private Uri saveBitmap(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/aaa");
        if (!file.exists())
            file.mkdirs();
        File imgFile = new File(file.getAbsolutePath() + "/1.jpeg");
        if (imgFile.exists())
            imgFile.delete();
        try {
            FileOutputStream outputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            Uri uri = Uri.fromFile(imgFile);
            return uri;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }






    /**
     * 上传图片到服务器
     *
     * @param bitmap
     */
    private void sendImage(Bitmap bitmap) {
        File file = new File(Environment.getExternalStorageDirectory() + "/aaa");
        if (!file.exists())
            file.mkdirs();
        File imgFile = new File(file.getAbsolutePath() + "/wechat_qr_code1.jpeg");
        if (imgFile.exists())
            imgFile.delete();
        try {
            FileOutputStream outputStream = new FileOutputStream(imgFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.flush();
            outputStream.close();
            init(imgFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        if(up){
            //新建线程加载图片信息，发送到消息队列中
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    Bitmap bmp = getURLimage(url);
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = bmp;
                    handle.sendMessage(msg);
                }
            }).start();
            Toast.makeText(WxImg.this, "刷新完毕", Toast.LENGTH_SHORT).show();
            up=false;//刷新一次即可，不需要一直刷新

        }
        super.onResume();
    }

    public void init (File file)
    {
        String id = null;
        try {
            Object user_info = Preferences.getParam(WxImg.this, "user_info", "");
            JSONObject myJson = null;
            myJson = new JSONObject(user_info.toString());
            id = myJson.get("id").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (FX_SignInUtil.switchAccount(WxImg.this)) {
            startActivity(new Intent(WxImg.this, Login.class));
        } else {
            OKManager.getInstance().type2019(id, file);
            Toast.makeText(WxImg.this, "上传成功", Toast.LENGTH_SHORT).show();
        }
    }
}

